<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\model\Config;
use think\facade\Validate;
use think\response\Json;

class AdminConfig extends AdminBase
{

	protected $middleware = [
        'app\middleware\AdminLogin',
		'app\middleware\AdminAuth'
	];

	private string $menuName = '系统配置';

    /**
     * 显示资源列表
     * @throws
     * @return Json
     */
    public function index():Json
    {
        $limit = input('pageSize/d',10);
        //分页配置
        $pageConfig = ['list_rows'=>$limit,'var_page'=>'pageNum'];

        $search = [
			[
				'label'=>'配置名称',//标签
				'prop'=> 'name',//表单名称
				'field'=> 'name',//查询字段
				'placeholder'=> '请输入配置名称',
				'required'=> false,//是否必填
				'expression'=> 'like',//查询表达式：like,not like,in,not in,between,not between,null,not null,time,>,<,>=,<=,=,<>(!=),find(FIND_IN_SET)
				'type'=> 'input',//类型：input,select,date,datetime,year,month,week,datetimerange,daterange
                'typeof' => 's',//强制转换类型：d整数，a数组，s字符串，b布尔类型，f浮点数
			],
		];

		$map = [];
        $this->setMap($search,$map);

		$data = Config::where($map)
			->order('id','asc')
			->paginate($pageConfig)
            ->each(function($item){
                $item['value'] = $item['type'] > 2 ? addDomain($item['value']):$item['value'];
                $item['value1'] = $item['type'] < 3 ? $item['value']:'';
                $item['value3'] = $item['type'] === 3 ? $item['value']:'';
                $item['value4'] = $item['type'] === 4 ? $item['value']:'';
                $item['value5'] = $item['type'] === 5 ? $item['value']:'';
                return $item;
            });

		$this->result['data'] = [
			'total' => $data->total(),
			'data' => $data->items(),
			'search' => $search
		];
		return returnAdmin($this->request,$this->result,$this->menuName.'-列表',$this->adminInfo);
    }

    /**
	 * 保存编辑的资源
	 * @throws
	 * @return Json
	 */
	public function save():Json
	{
		//获取form表单
		$param = input('param.',[]);
		$param = toUnderline($param);

		try{

			$model = new Config();
			$fields = $model->getFields();
			$pk = $model->getPk();
			$id = $param[$pk] ?? 0;

			$rule = [
				'var_name' => 'require|max:64|unique:config,var_name,'.$id.','.$pk,
				'type' => 'require|in:1,2,3,4,5',
				'name' => 'require|max:255',
			];
			$message = [
				'var_name.require' => '菜单名称必填',
				'var_name.max' => '菜单名称最多64个字符',
				'type.require' => '类型必填',
				'type.in' => '类型只能是1-5的数字',
				'name.require' => '路由名称必填',
				'name.max' => '路由名称最多64个字符'
			];
			$validate = Validate::rule($rule)->message($message);

			if(!$validate->check($param)){
				throw new \Exception($validate->getError());
			}

            if($param['type'] > 2){//图片、视频、文件去除域名保存
                $param['value'] = removeDomain($param['value']);
            }

			if(!$id){
				//新增
				$model->create($param,$fields);
			}else{
				//修改
				$info = $model->find($id);
				if(!$info){
					throw new \Exception('无效参数');
				}
                //删除旧的图片、视频、文件
                if($info['type'] > 2 && $info['value'] && $info['value'] != $param['value']){
                    if(is_file('.'.$info['value'])){
                        @unlink('.'.$info['value']);
                    }
                }

				$info->allowField($fields)->save($param);
			}

		}catch (\Exception $e){
			$this->result['code'] = 500;
			$this->result['msg'] = $e->getMessage();
		}
		return returnAdmin($this->request,$this->result,$this->menuName.'-编辑',$this->adminInfo);
	}



    /**
     * 删除指定资源
     * @throws
     * @return Json
     */
    public function delete():Json
    {

        try{
            $id = (string) input('id','');
            if(!$id){
                throw new \Exception('未选择数据');
            }
            $info = Config::find($id);
            if(!$info){
                throw new \Exception('无效的数据');
            }
            if($info['is_del']){
                throw new \Exception('关键配置，不能删除');
            }
            $type = $info['type'];
            $value = $info['value'];
            $info->delete();
            //删除文件
            if($type > 2 && is_file('.'.$value)){
                @unlink('.'.$value);
            }

            $this->result['msg'] = '删除ID：'.$id;
        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }


        return returnAdmin($this->request,$this->result,$this->menuName.'-删除',$this->adminInfo);
    }

}
